import time,re
import pandas as pd
import redis
import pickle
import logging
import hashlib
import configparser
import datetime
from sqlalchemy import create_engine, DateTime, String
import pymysql
import traceback

import warnings

# 忽略所有警告
warnings.filterwarnings('ignore')


pymysql.install_as_MySQLdb()


log_format = "%(asctime)s - %(levelname)s - %(process)d - %(filename)s:%(lineno)d - %(message)s"
date_format = "%Y-%m-%d %H:%M:%S"  # 精确到秒
logging.basicConfig(level=logging.DEBUG, format=log_format, datefmt=date_format)

# 初始化配置解析器
config = configparser.ConfigParser()

import os
current_dir = os.path.dirname(os.path.abspath(__file__))
config.read(current_dir+'/config.ini')


# 获取Redis的配置信息
redis_host = config.get('Redis', 'host')
# redis_host = "192.168.249.10"

redis_port = config.getint('Redis', 'port')
redis_db = config.getint('Redis', 'db')
redis_password = config.get('Redis', 'password')
r = redis.Redis(host=redis_host, port=redis_port, db=redis_db, password=redis_password)

mysql_port = config.getint('mysql', 'port')
mysql_host = config.get('mysql', 'host')
mysql_db = config.get('mysql', 'db')
import urllib.parse
mysql_password = urllib.parse.quote(config.get('mysql', 'password'))
mysql_user = config.get('mysql', 'user')
db_url = f'mysql://{mysql_user}:{mysql_password}@{mysql_host}:{mysql_port}/{mysql_db}'
engine = create_engine(db_url,pool_size=20,max_overflow=20,pool_recycle=60)


def get_brand_and_concept_rank(query_date,stock_name):

    stock_fupan_df = pickle.loads(r.get(f"stock_panqian:{query_date}"))

    stock_fupan_df =stock_fupan_df.query(f'股票简称 == "{stock_name}"')

    real_stock_info_tdx = pickle.loads(r.get("real_stock_info_tdx"))

    stock_fupan_df = stock_fupan_df.dropna()
    stock_fupan_df['所属同花顺行业'] = stock_fupan_df['所属同花顺行业'].str.replace("-", ";")
    stock_fupan_df['所属概念'] = stock_fupan_df['所属概念'] + ";" + stock_fupan_df['所属同花顺行业']
    stock_fupan_df['所属概念'] = stock_fupan_df['所属概念'].str.split(';')
    stock_concept_mapping_df = stock_fupan_df.explode('所属概念')
    #股票于板块的映射关系
    stock_concept_mapping_df = stock_concept_mapping_df[["股票代码",'股票简称',"所属概念"]]
    #股票-概念-涨幅的关系


    concept_df = pickle.loads(r.get("real_market_concept_index_tdx"))
    stock_concept_mapping_tdx_df = pd.merge(stock_concept_mapping_df,concept_df,how="inner",left_on="所属概念",right_on="concept_name")






    stock_result={}
    stock_result["name"] = stock_name

    #取涨幅最大的概念
    largest_change_hs_row = stock_concept_mapping_tdx_df.nlargest(1, 'change_hs')

    try:
        logging.info(f"股票名称：{largest_change_hs_row['股票简称'].values[0]}")
        logging.info(f"最强概念：{largest_change_hs_row['concept_name'].values[0]}")
        #合并最强概念以及它们的相似概念
        logging.info(f"相似概念：{largest_change_hs_row['相似概念'].values[0]}")
        logging.info(f"原有概念：{largest_change_hs_row['所属概念'].values[0]}")

        largest_change_hs_row['相关概念'] = largest_change_hs_row['所属概念'] + ";" + largest_change_hs_row['相似概念']
        largest_change_hs_row['相关概念'] = largest_change_hs_row['相关概念'].str.split(';')
        largest_change_hs_row = largest_change_hs_row.explode('相关概念')
        largest_change_hs_row = pd.merge(largest_change_hs_row[["股票代码","股票简称","所属概念","相关概念"]],concept_df,how="inner",left_on="相关概念",right_on="concept_name")
        # 取涨幅最大的相关概念
        concpet_df = largest_change_hs_row.nlargest(1, 'change_hs')



    except Exception as e:
        tb_info = traceback.format_exc()
        # 将异常信息和 traceback 信息一起记录
        logging.info(f"An error occurred: {e}\nTraceback info:\n{tb_info}")
        # logging.info(concpet_df)
        # logging.info(real_stock_info_tdx["timestamp"].values[0])

    stock_result["concept_name_ori"] = concpet_df['所属概念'].values[0]
    stock_result["concept_name"] = concpet_df['concept_name'].values[0]
    stock_result["concept_change"] = concpet_df['change'].values[0]
    stock_result["concept_change_hs"] = concpet_df['change_hs'].values[0]
    stock_result["zt_10cm"] = concpet_df['zt_10cm'].values[0]
    stock_result["zt_20cm"] = concpet_df['zt_20cm'].values[0]
    stock_result["concept_change_rps"] = concpet_df['change_rps'].values[0]
    stock_result["concept_change_hs_rps"] = concpet_df['change_hs_rps'].values[0]



    return stock_result



if __name__ == "__main__":
    # logging.info("个股行业与概念涨幅排名分析开始监听:")
    pd.set_option('display.max_columns', None)
    query_date = datetime.datetime.now().strftime('%Y%m%d')
    query_date = '20240605'
    print(get_brand_and_concept_rank(query_date,'航天电器'))










